<template>
  <span style="text-align:left;padding-left:8rpx;">
    <el-button type="success" size="medium" @click="dialogVisible = true">批量同步</el-button>
    <el-dialog
      title="批量增加门店产品"
      :visible.sync="dialogVisible"
      width="80%"
    >
      <div>
        <div>
          <div style="padding:10px">
            <el-divider>同步门店</el-divider>
            <!-- <el-transfer v-model="storeIds" :data="stores" filterable /> -->
            <el-select v-model="storeId" clearable placeholder="操作门店">
              <el-option
                v-for="item in stores"
                :key="item.key"
                :label="item.label"
                :value="item.key"
              />
            </el-select>
            <el-select v-model="categoryId" filterable placeholder="产品类型" style="margin-left:10px" @change="getSpecifications">
              <el-option-group v-for="type in categories" :key="type.id" :label="type.name" :value="type.id">
                <el-option v-for="category in type.children" :key="category.id" :label="category.__toString" :value="category.id" />
              </el-option-group>
            </el-select>
          </div>
          <div style="padding:10px">
            <el-divider>同步产品</el-divider>
            <div style="margin-top:10px">
              <el-transfer v-model="specificationIds" :data="specifications" filterable />
            </div>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </div>
    </el-dialog>
  </span>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      stores: [],
      storeId: '',
      categories: [],
      categoryId: '',
      specifications: [],
      specificationIds: []
    }
  },
  created() {
    this.getStores()
    this.axios.get(`/manage/categories`, { params: {
      '@filter': `!entity.getParent() && entity.getType().getSlug() == "ProductCategory" `,
      '@expands': `['entity.children']`
    }}).then((res) => {
      for (const i of res.data) {
        for (const c in i.children) {
          if (i.children[c].__metadata.type.id != 1) {
            i.children.splice(c, 1)
          }
        }
      }
      this.categories = res.data
    })
  },
  methods: {
    getStores() {
      this.storeIds = []
      this.axios.get(`/manage/stores`, { params: {
        '@display': `{
        'key': 'entity.getId()',
        'label': 'entity.getName()'
      }`
      }}).then((res) => {
        console.log('res', res)
        this.stores = res.data
      })
    },
    getSpecifications() {
      console.log(this.categoryId)
      if (this.categoryId === '') {
        this.$message.error('请先选择产品类型')
        return
      }
      this.axios.get(`/manage/specifications`, {
        params: { '@filter': `entity.getProduct().getCategory().getId() == ${this.categoryId} && entity.getProduct().getIsOnSale() == true` }
      }).then((res) => {
        console.log('specifications', res.data)
        const specifications = []
        for (const i of res.data) {
          specifications.push({
            label: `${i.product.__toString}(${i.price})`,
            key: i.id
          })
        }
        this.specifications = specifications
      })
    },
    submit() {
      console.log(this.storeId, this.specificationIds)
      if (this.storeId !== '') {
        const loading = this.$loading({
          lock: true,
          text: '门店产品数据同步中....',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        const storeSpecifications = []
        // 先查这个store对应类型的所有storeSpecification，筛选出来，避免报错
        this.axios.get(`/manage/store-specifications`, { params: {
          '@filter': `entity.getSpecification().getProduct().getCategory().getId() == ${this.categoryId} && entity.getStore().getId() == ${this.storeId}`
        }}).then((res) => {
          const oldStoreSpecifications = res.data
          console.log('已经有的s', oldStoreSpecifications)
          for (const i of oldStoreSpecifications) {
            const index = this.specificationIds.indexOf(i.specification.id)
            if (index != -1) {
              this.specificationIds.splice(index, 1)
            }
          }
          console.log('筛选后的id', this.specificationIds)
          for (const spec of this.specificationIds) {
            storeSpecifications.push({
              specification: spec,
              store: this.storeId,
              price: 0,
              listOrder: 255
            })
          }
          console.log('最终需要记录的', storeSpecifications)
          this.axios.post(`/manage/store-specifications`, storeSpecifications).then((res) => {
            loading.close()
            // this.dialogVisible = false
            this.specificationIds = []
            this.$message.success('操作成功！')
            // location.reload()
          }).catch(() => { loading.close() })
        })
      } else {
        this.$message.error('请选择门店！')
      }
    }
  }
}
</script>

